{% extends "base.html" %}

{% block content %}
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">
            {% if mode == 'create' %}Create New API{% else %}Edit API: {{ api_name }}{% endif %}
        </h6>
    </div>
    <div class="card-body">
        {% if error %}
        <div class="alert alert-danger">{{ error }}</div>
        {% endif %}
        
        {% if api and api.get('load_error') %}
        <div class="alert alert-danger">
            <strong>Script Error:</strong> {{ api.load_error }}
        </div>
        {% endif %}

        <!-- 保存状态提示 -->
        <div id="saveStatus" class="alert alert-info alert-dismissible fade show" style="display: none; position: fixed; top: 20px; right: 20px; z-index: 1000; min-width: 300px;">
            <span id="saveMessage"></span>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>

        <form method="POST" id="apiForm">
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="apiName" class="form-label">API Name *</label>
                        <input type="text" class="form-control" id="apiName" name="api_name"
                               value="{{ api_name if mode == 'edit' else '' }}" required>
                        <div class="form-text">A descriptive name for your API</div>
                    </div>

                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="2">{{ description if mode == 'edit' else '' }}</textarea>
                        <div class="form-text">Optional description of your API</div>
                    </div>

                    <div class="mb-3">
                        <label for="custom_prefix" class="form-label">API Path Prefix</label>
                        <input type="text" class="form-control" id="custom_prefix" name="custom_prefix"
                               value="{{ custom_prefix }}">
                        <div class="form-text">Custom prefix for your API endpoints (e.g. /api/v1)</div>
                    </div>

                     <!-- 鉴权设置 -->
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="authRequired"
                                   name="auth_required" {% if auth_required %}checked{% endif %}>
                            <label class="form-check-label" for="authRequired">
                                Require Authentication
                            </label>
                        </div>
                        <div class="form-text">
                            Enable to require authentication for accessing this API's endpoints
                        </div>
                    </div>

                    <!-- 鉴权类型选择 -->
                    <div class="mb-3">
                        <label class="form-label">Authentication Type</label>
                        <select class="form-select" name="auth_type">
                            {% for auth_type in auth_types %}
                            <option value="{{ auth_type }}" {% if auth_type == auth_type %}selected{% endif %}>
                                {{ auth_type|capitalize }}
                            </option>
                            {% endfor %}
                        </select>
                        <div class="form-text">
                            Select the authentication method for this API
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="alert alert-info">
                        <h6 class="alert-heading">
                            <i class="bi bi-info-circle me-1"></i> API Creation Guidelines
                        </h6>
                        <ul class="mb-0 mt-2">
                            <li>Each function you define will become an API endpoint</li>
                            <li>Functions should return JSON-serializable data (dict, list, etc.)</li>
                            <li>Use docstrings to describe your functions - they will appear in API documentation</li>
                            <li>API endpoints will be protected with API key authentication</li>
                            <li>You can customize the API path prefix for this API</li>
                            <li class="text-primary"><strong>Tip:</strong> Use Ctrl+S to save your changes</li>
                        </ul>
                    </div>

                    {% if mode == 'edit' %}
                    <div class="alert alert-warning">
                        <h6 class="alert-heading">
                            <i class="bi bi-exclamation-triangle me-1"></i> Important
                        </h6>
                        <p class="mb-0">Editing the API will clear the module cache and reload the script. Any active connections using the old version may be affected.</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <div class="mb-4">
                <label for="script" class="form-label">Python Script *</label>
                <div class="editor-container mb-2">
                    <!-- 使用与base.html相同的编辑器容器 -->
                    <div id="editor" data-initial-value="{% if mode == 'edit' %}{{ script_content }}{% else %}# Write your Python script here
# Define functions that will become API endpoints

def hello_world(name: str = 'World') -> dict:
    &quot;&quot;&quot;Returns a greeting message
    Args:
        name: Name to greet (default: 'World')
    Returns:
        dict: Greeting message
    &quot;&quot;&quot;
    return {'message': f'Hello, {name}!'}

def calculate_sum(a: float, b: float) -> dict:
    &quot;&quot;&quot;Calculates the sum of two numbers
    Args:
        a: First number
        b: Second number
    Returns:
        dict: Calculation result
    &quot;&quot;&quot;
    return {'result': a + b}

def get_user_info(user_id: int) -> dict:
    &quot;&quot;&quot;Get user information (simulated)
    Args:
        user_id: User ID to retrieve
    Returns:
        dict: User information or error
    &quot;&quot;&quot;
    users = {
        1: {&quot;name&quot;: &quot;Alice&quot;, &quot;email&quot;: &quot;alice@example.com&quot;},
        2: {&quot;name&quot;: &quot;Bob&quot;, &quot;email&quot;: &quot;bob@example.com&quot;}
    }
    return users.get(user_id, {&quot;error&quot;: &quot;User not found&quot;}){% endif %}"></div>
                </div>
                <textarea name="script" id="scriptTextarea" class="d-none">{% if mode == 'edit' %}{{ script_content }}{% endif %}</textarea>

                {% if mode == 'edit' and api.functions %}
                <div class="mt-4">
                    <h5>Function Path Settings</h5>
                    <div class="alert alert-info">
                        Customize paths for each function. Leave blank to use default paths.
                    </div>

                    <div class="row">
                        {% for func_name, func in api.functions.items() %}
                        <div class="col-md-6 mb-3">
                            <div class="card">
                                <div class="card-body">
                                    <h6 class="card-title">
                                        <code>{{ func_name }}</code>
                                    </h6>
                                    <div class="mb-2">
                                        <label class="form-label">Custom Path</label>
                                        <div class="input-group">
                                            <span class="input-group-text">/</span>
                                            <input type="text" class="form-control"
                                                   name="path_{{ func_name }}"
                                                   value="{{ func.custom_path[1:] if func.custom_path else '' }}"
                                                   placeholder="custom/path">
                                        </div>
                                        <div class="form-text">
                                            Default: <code>{{ func.default_path }}</code>
                                        </div>
                                    </div>
                                    <p class="card-text small text-muted">
                                        {{ func.description|default('No description', true) }}
                                    </p>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>

            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    {% if mode == 'create' %}<i class="bi bi-plus-circle me-1"></i> Create API{% else %}<i class="bi bi-save me-1"></i> Update API{% endif %}
                </button>
                <a href="{{ url_for('index') }}" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 显示保存状态消息
        function showSaveStatus(message, type) {
            var statusElement = document.getElementById('saveStatus');
            var messageElement = document.getElementById('saveMessage');

            statusElement.className = 'alert alert-' + type + ' alert-dismissible fade show';
            messageElement.textContent = message;
            statusElement.style.display = 'block';

            // 5秒后自动隐藏
            setTimeout(function() {
                statusElement.style.display = 'none';
            }, 5000);
        }

        // 监听Ctrl+S快捷键
        document.addEventListener('keydown', function(e) {
            // 检查是否按下Ctrl+S或Cmd+S (Mac)
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault(); // 阻止默认保存行为

                // 确保编辑器内容已同步
                updateEditorContent();

                // 显示保存中状态
                showSaveStatus('Saving changes...', 'info');

                // 提交表单
                document.getElementById('apiForm').submit();
            }
        });

        // 表单提交时也显示状态
        document.getElementById('apiForm').addEventListener('submit', function() {
            showSaveStatus('Saving changes...', 'info');
        });
    });
</script>
<style>
    .alert.fixed {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1000;
    }
</style>
{% endblock %}